package com.samen.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.os.AsyncTask;

/**
 * @author Santosh Kumar D
 * 
 *         It downlaods file from a location given in the execute method and saves the content to file
 * 
 */
public class DownloadTask extends AsyncTask<String, Integer, Boolean> {
	ProgressDialog progressDialog;
	DownloadProgressListener downloadProgressListener;
	File destFile;

	/**
	 * 
	 * @param downloadProgressListener
	 *            - interface to receive progress updates
	 * @param file
	 *            - file that should be saved
	 */
	public DownloadTask(DownloadProgressListener downloadProgressListener, File file) {
		super();
		this.downloadProgressListener = downloadProgressListener;
		this.destFile = file;
	}

	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		downloadProgressListener.downloadProgress(values[0]);
	}

	@Override
	protected Boolean doInBackground(String... params) {
		HttpClient httpClient = new DefaultHttpClient();
		HttpGet request = new HttpGet(params[0]);
		FileOutputStream fileOutputStream;
		try {
			HttpResponse response = httpClient.execute(request);
			InputStream in = response.getEntity().getContent();
			fileOutputStream = new FileOutputStream(destFile);

			String value = response.getLastHeader("Content-Length").getValue();
			int len = Integer.parseInt(value);
			int count = 0, tmp = 0;
			byte[] bytes = new byte[1024];

			while ((tmp = in.read(bytes)) > -1) {
				if (isCancelled()) {
					destFile.delete();
					break;
				}
				fileOutputStream.write(bytes, 0, tmp);
				count = count + tmp;
				double d = count / (float) len;
				publishProgress((int) (d * 100));
			}
			in.close();
			fileOutputStream.close();
			return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	protected void onPostExecute(Boolean result) {
		super.onPostExecute(result);
		downloadProgressListener.downloadComplete(result);
	}

	public interface DownloadProgressListener {

		/**
		 * 
		 * @param progress
		 *            - int between 0 and 100(inclusive)
		 */
		public void downloadProgress(int progress);

		/**
		 * 
		 * @param success
		 */
		public void downloadComplete(boolean success);

	}
}